package miao_ser

import (
	"encoding/json"
	"gitee.com/ling1314/origin-utility/constant"
	"gitee.com/ling1314/origin-utility/db"
	"gitee.com/ling1314/origin-utility/model"
	"gitee.com/ling1314/origin-utility/utils"
	log "github.com/sirupsen/logrus"
	"net"
	"time"
)

func (s *TcpServer) HandMsg(m model.ClientResponse, conn net.Conn) {
	// 通过 ClientType 处理不同系统的客户端， 通过 Timely 对离线数据和实时数据分别处理。现在还用不到，预留的字段
	switch m.Code {
	case constant.Heartbeat:
		s.handlePing(m)
	case constant.WhoAmiForIdp:
		s.HandleViHandsUp(m, conn)
	case constant.GuarderPipMsg:
		s.viHandler.HandleGuarderPipMsg(m)
	case constant.ExecutePlugin:
		switch m.ClientType {
		case "vi-client":
			s.viHandler.HandleCliMsg(m)
		case "va-host":
		default:
			log.Error("undefined client type")
		}
	default:
		log.Debug("undefined messages:", m)
	}

}

func (s *TcpServer) handlePing(m model.ClientResponse) {
	var (
		p model.PingPcLoad
		c db.IdpCatch
	)
	if err := json.Unmarshal([]byte(m.Content.Result), &p); err != nil {
		log.Error(err)
		return
	}
	if _, ok := db.InfoCatchMaoForIdp[m.DeviceId]; ok {
		c = db.InfoCatchMaoForIdp[m.DeviceId]
		c.CpuPer = p.CPU
		c.MemoryPer = p.Memory
		db.InfoCatchMaoForIdp[m.DeviceId] = c
	}
}

// HandleViHandsUp 处理miao模块客户端的举手信息
func (s *TcpServer) HandleViHandsUp(m model.ClientResponse, conn net.Conn) {
	var (
		bi       model.HandsUpMsgForVi
		clientId int64
		err      error
	)
	err = json.Unmarshal([]byte(m.Content.Result), &bi)
	if err != nil {
		log.Errorf("不合法的 HandsUp 消息：%v", m)
		return
	}
	if clientId, err = s.viHandler.getDeviceId(model.HandsUpMsgForVi{
		Md5:             bi.Md5,
		BiosSerial:      bi.BiosSerial,
		MainBoardSerial: bi.MainBoardSerial,
		HardDiskSerial:  bi.HardDiskSerial,
		ActiveMAC:       bi.ActiveMAC,
		IP:              bi.IP,
		Hostname:        bi.Hostname,
	}); err != nil {
		log.Error(err)
		return
	}
	if clientId > 0 {
		s.clientOnline(clientId, conn)
		// todo  2014-03-28将消息缓存，这里需要缓存全量信息，后面在修改
		db.InfoCatchMapForVa[clientId] = bi
		err = sendInstructForSetDeviceId(clientId, conn)
		if err != nil {
			log.Error("通知客户端设置ID失败,err:", err)
		}
	} else {
		clientId = utils.GetSoftId()
		s.clientOnline(clientId, conn)
		db.AbnormalDeviceForIdp[clientId] = db.AbnormalDevice{
			HandsUpMsg: bi,
			Conn:       conn,
		}
	}
	s.StartGuarder(clientId)
}

// StartGuarder  启动守卫进程
func (s *TcpServer) StartGuarder(clientId int64) {
	cliPlu := model.PluginInstruct{
		Cmd:  "guarder",
		Args: []string{"-c=90", "-m=0.9"}, //todo cpu 信息采集存在很大差距，后面在调整这个值
	}
	bs, err := json.Marshal(cliPlu)
	if err != nil {
		log.Error(err)
		return
	}
	inst := model.ClientInstruct{
		Code:      constant.StartGuarder,
		ServeTime: time.Now().Unix(),
		Body:      string(bs),
	}
	err = SendInstruct(clientId, inst)
	if err != nil {
		log.Error(err)
	}
}
